package finder;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import applicationDAO.InstituteDAO;

import com.project.trac.R;

import core.modules.DatabaseConnector;


public class SubjectFinder extends InstituteDAO {

	private String REGISTRATION_CODE;
	private String CATALOG_NUMBER;

	private AlertDialog.Builder alertDialog;
	private Dialog dialog;
	private TextView textView;
	private View layout;

	private EditText et_RegistrationCode;
	private TextView textView2;
	private ViewGroup root;
	
	int remaining;
	int max;
	

	public static ListFragment newInstance(Context context) {
		SubjectFinder lf = new SubjectFinder();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		root = (ViewGroup) inflater.inflate(R.layout.generic_list_a, null);
		
		new AsynchronousTask("initialize").execute();

		root.setFocusableInTouchMode(true); 	//this line is important

		dialog = new Dialog(getActivity());
		dialog.setCancelable(true);
		alertDialog = new AlertDialog.Builder(getActivity());
		alertDialog.setTitle("Information");
		alertDialog.setIcon(android.R.drawable.ic_dialog_info);
		alertDialog.setCancelable(true);
		
		textView = new TextView(getActivity());
		textView.setTextAppearance(getActivity(), R.style.alert_message);
		textView.setGravity(Gravity.CENTER_HORIZONTAL);

		layout = View.inflate(getActivity().getApplicationContext(), R.layout.generic_dialog_box, null);
		et_RegistrationCode = (EditText) layout.findViewById(R.id.dialogInput);
		
		textView2 = (TextView) layout.findViewById(R.id.dialogSpiel);
		textView2.setText("Please enter the registration code\nprovided by your instructor");
		textView2.setGravity(Gravity.CENTER);
		
		alertDialog.setPositiveButton("Enroll", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d,int id) {
				
				//TODO: for code review ; shows invalid code for registration
				if (remaining == 0) {
					Toast.makeText(getActivity(), "Schedule is full!", Toast.LENGTH_LONG).show();
					d.dismiss();
				} else { 
					int ctr = 0;
					if (et_RegistrationCode.getText().toString().equals(REGISTRATION_CODE)) {
						
						Toast.makeText(getActivity(), "You have joined " + CATALOG_NUMBER + ".", Toast.LENGTH_LONG).show();
						new AsynchronousTask("register").execute();
						d.dismiss();
						
					} else { 
						Toast.makeText(getActivity(), "Invalid registration code.", Toast.LENGTH_LONG).show();
						ctr++;
						if (ctr == 3) {
							textView.setText("Invalid registration for 3 times, \n please try again.");
							alertDialog.setTitle("Alert!");
							alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
							alertDialog.setView(textView);
							alertDialog.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface d, int arg1) {
									d.dismiss();
								}
							});
							
						}
					}
				}
				
				/* code fix to remove current view and return to parent activity*/
				((ViewGroup) layout.getParent()).removeView(layout);
				getActivity().startActivity(getActivity().getIntent());
			}
		});
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d,int id) {
				d.dismiss();
				((ViewGroup) layout.getParent()).removeView(layout);
			}
			
		});
		
		
		return root;
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		OnItemClickListener joinGroup = new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				ArrayList<String> list = new ArrayList<String>();
				
				Object data = av.getItemAtPosition(position);
				
				StringTokenizer tokenizer = new StringTokenizer(data.toString(),",=");
				
				while (tokenizer.hasMoreTokens() ) {  
					list.add(tokenizer.nextToken());  
				}  
				
				setSubjectID(String.valueOf(list.get(list.indexOf(" k8")+1)));
				REGISTRATION_CODE = list.get(list.indexOf(" k7")+1);
				CATALOG_NUMBER = list.get(list.indexOf(" k1")+1);
				
				dialog = alertDialog.setTitle("Join " + CATALOG_NUMBER + "?").setView(layout).create();
				
				if (dialog != null) {
					dialog.show();
				} else {
					dialog.cancel();
				}
				
			}
			
			
		};

		getListView().setOnItemClickListener(joinGroup);

	}

	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	public void onSaveInstanceState(Bundle outState) {
		outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
		super.onSaveInstanceState(outState);
	}

	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ProgressDialog progressDialog;
		ListAdapter listAdapter;

		String KEY_CAT = "k1";
		String KEY_SECTION = "k2";
		String KEY_DAYS = "k3";
		String KEY_TIME = "k4";
		String KEY_ROOM = "k5";
		String KEY_INSTRUCTOR = "k6";
		String KEY_CODE = "k7";
		String KEY_CURRICULUM_ID = "k8";
		String KEY_SLOTS_LEFT = "k9";
		String VALUE_INSTRUCTOR = "instructor name";

		int rowCount;
		
		ResultSet rs;
		PreparedStatement pps;
		String command = "command";

		AsynchronousTask(String command)
		{
			doInBackground(command);
			this.command = command;
		}
		

		protected void onPreExecute() {
			super.onPreExecute();

			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setTitle("Please Wait");
			progressDialog.setMessage("Querying the database.");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {
			
			try {
				if (command.equalsIgnoreCase("initialize")) {
					initialize();
				} // --- end initialize
				
				if (command.equalsIgnoreCase("register")) {
					DatabaseConnector.setPreparedStatement
					("INSERT INTO gradesheet (uid, catalognumber) VALUES " + "(?,?)");
					pps = DatabaseConnector.getPreparedStatement();
					
					try {
						pps.setInt(1, getUserID());
						pps.setInt(2, getSubjectID());
	
						pps.executeUpdate();
					} catch (SQLException e) {
						Log(getClass(), "doInBackground", e);
					}
					pps.close();
					initialize();
				} // --- end register

			} catch (SQLException e) {
				Log(getClass(), "doInBackground, command: " + command, e);
			}
			
			return null;
		}
		
		protected void onPostExecute(String postExecute) {
			
			TextView msg = new TextView(getActivity());
			
			if (rowCount == 0) {
				msg.setText("You are not yet enrolled to any subject.");
			} else if (rowCount == 1) {
				msg.setText("Found " + rowCount + " subject.");
			} else if (rowCount > 1) {
				msg.setText("Found " + rowCount + " subjects!");
			}

			msg.setTextAppearance(getActivity(), R.style.alert_message);
			msg.setGravity(Gravity.CENTER_HORIZONTAL);

			new AlertDialog.Builder(getActivity())
			.setTitle("Information")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(msg)
			.setCancelable(false)
			.setPositiveButton(android.R.string.ok, 
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}
			}).create().show();

			progressDialog.dismiss();

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter = new SimpleAdapter(getActivity(), arrayList,
							R.layout.detail_result_course_finder, 
							new String[] { KEY_CAT, KEY_SECTION,  KEY_DAYS,  KEY_TIME,  
										   KEY_ROOM,  KEY_INSTRUCTOR, KEY_CODE, KEY_SLOTS_LEFT}, 
							new int[] { R.id.r_key_cat_new, R.id.actualSection,  R.id.actualDay, 
										R.id.actualTime,  R.id.actualRoom,  R.id.actualInstructor, 0, R.id.actualSlots});

					setListAdapter(listAdapter);
				}
			});

		}

		private void initialize() throws SQLException {
		//FIXME: slots left does not display in ui
		//FIXME: time must be formatted (NewSchedule.class)
					rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT schedule.section, schedule.room, schedule.days, schedule.time, schedule.code,"
							   + " users.title, users.firstname, users.lastname, schedule.max,"
							   + " curriculum.catalognumber, curriculum.id,"
							   + " (SELECT (schedule.max - COUNT(gradesheet.uid))"
							   + " FROM GRADESHEET"
							   + " WHERE gradesheet.catalognumber = schedule.id) AS 'remaining'"
							   + " FROM schedule "
							   + " INNER JOIN users ON users.id = schedule.creator"
							   + " INNER JOIN curriculum ON curriculum.id = schedule.catalognumber"
							   + " WHERE curriculum.id NOT IN "
							   + " (SELECT catalognumber FROM gradesheet WHERE uid=" + getUserID()
							   + " ) ORDER BY schedule.catalognumber ASC");

					while (rs.next()) {
						VALUE_INSTRUCTOR = 
								rs.getString("title")  + " " + 
								rs.getString("firstname")  + " " + 
								rs.getString("lastname");

						remaining = rs.getInt("remaining");
						max = rs.getInt("max");
						
						m = new HashMap<String, String>();
						m.put(KEY_CAT, rs.getString("catalognumber"));
						m.put(KEY_SECTION, rs.getString("section"));
						m.put(KEY_DAYS, rs.getString("days"));
						m.put(KEY_TIME, rs.getString("time"));
						m.put(KEY_ROOM, rs.getString("room"));
						m.put(KEY_INSTRUCTOR, VALUE_INSTRUCTOR);
						m.put(KEY_CURRICULUM_ID, rs.getString("curriculum.id"));
						m.put(KEY_SLOTS_LEFT, String.valueOf(remaining));

						arrayList.add(m);

					}
					rowCount = rs.last() ? rs.getRow() : 0;
					rs.close();
		}
		
		
	} 
	
}